<?php

namespace common\web;

use Yii;
use yii\helpers\Html;

/**
 * View represents a view object in the MVC pattern.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class View extends \yii\web\View {

    /**
     * @var string the context assets path.
     */
    public $icon = false;

    /**
     * @var string the context assets path.
     */
    public $description;

    /**
     * @var string the context assets path.
     */
    public $assetsPath;

    public function getPublishedUrl() {
        return $this->assetManager->getPublishedUrl($this->assetsPath);
    }

    /**
     * Renders a view in response to an AJAX request.
     *
     * This method is similar to [[render()]] except that it will surround the view being rendered
     * with the calls of [[beginPage()]], [[head()]], [[beginBody()]], [[endBody()]] and [[endPage()]].
     * By doing so, the method is able to inject into the rendering result with JS/CSS scripts and files
     * that are registered with the view.
     *
     * @param string $view the view name. Please refer to [[render()]] on how to specify this parameter.
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
     * @param object $context the context that the view should use for rendering the view. If null,
     * existing [[context]] will be used.
     * @return string the rendering result
     * @see render()
     */
    public function renderAjax($view, $params = [], $context = null) {
        $viewFile = $this->findViewFile($view, $context);
        ob_start();
        ob_implicit_flush(false);
        $this->beginPage();
        $this->head();
        $this->beginBody();
        $content = $this->renderFile($viewFile, $params, $context);
        if (Yii::$app->getRequest()->isModal) {
            $this->beginModal();
        }
        echo $content;
        $this->endBody();
        $this->endPage(true);
        return ob_get_clean();
    }

    /**
     * Marks the position of an HTML head section.
     */
    public function beginModal() {
        $title = Html::encode($this->title ?: 'Modal');
        if ($this->icon !== false) {
            $title = Html::tag('i', '', ['class' => $this->icon]) . $title;
        } else {
            $title = Html::tag('span', $title);
        }
        $closeButton = Html::button('', ['class' => 'close', 'data-dismiss' => 'modal', 'aria-hidden' => 'true']);
        $modelTitle = Html::tag('h3', $title, ['class' => 'modal-title']);
        echo Html::tag('div', $closeButton . $modelTitle, ['class' => 'modal-header']);
    }

}
